package com.tanhua.app.Service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SoundVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private SoundApi soundApi;

    @DubboReference
    private UserInfoApi userInfoApi;


    //查询剩余发送次数的key
    private static final String SEND_TIME = "USER_SEND_TIME_";

    //查询剩余接受次数的key
    private static final String ACCEPT_TIME = "USER_ACCEPT_TIME_";


    //计算第二天凌晨与当前时间的时间差秒数(毫秒值)
    public static Long getNowToNextDaySeconds() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }


    //发送语音
    public void sendSound(MultipartFile soundFile) {
        //定义查询key
        String key = SEND_TIME + UserHolder.getUserId();
        //先从redis中查询剩余发送次数
        String time = redisTemplate.opsForValue().get(key);
        //如果没有查到,则为当天第一次发送,并将该次数存储到redis中,时效为当前时间到次日凌晨0点的时间间隔
        if (StringUtils.isBlank(time)) {
            redisTemplate.opsForValue().set(key, "10", getNowToNextDaySeconds(), TimeUnit.SECONDS);
        } else if ("0".equals(time)) {
            //如果查到次数为0,则直接抛出异常
            throw new BusinessException(ErrorResult.sendTimeError());
        }
		time = redisTemplate.opsForValue().get(key);

        try {
            //调用FastDFS上传语音文件，返回url
            InputStream inputStream = soundFile.getInputStream();
            String originalFilename = soundFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            StorePath storePath = client.uploadFile(inputStream, soundFile.getSize(), extName, null);
            String soundUrl = webServer.getWebServerUrl() + storePath.getFullPath();
            //构造sound对象,调用dubbo服务
            Sound sound = new Sound();
            sound.setUserId(UserHolder.getUserId());
            sound.setSoundUrl(soundUrl);
            soundApi.send(sound);
            //发送成功,则将redis中的剩余发送次数减1
            Integer i = Integer.valueOf(time);
            i -= 1;
            redisTemplate.opsForValue().set(key, i.toString(), getNowToNextDaySeconds(), TimeUnit.SECONDS);
        } catch (IOException e) {
            throw new RuntimeException("语音发送失败!");
        }
    }

    //接收语音
    public SoundVo getSound() {
        //定义查询key
        String key = ACCEPT_TIME + UserHolder.getUserId();
        //先从redis中查询剩余接受次数
        String time = redisTemplate.opsForValue().get(key);
        //如果为空,则为今天第一次接收语音,将对应的值设置到redis中
        if (StringUtils.isBlank(time)) {
            redisTemplate.opsForValue().set(key, "10", getNowToNextDaySeconds(), TimeUnit.SECONDS);
        } else if ("0".equals(time)) {
            //如果为0,则表示没有接收次数了,抛出异常
            throw new RuntimeException("今日接收次数已用完");
        }
		time = redisTemplate.opsForValue().get(key);
        //为其他值,正常接受语音信息
        //调用api ,查询一个state为0的语音信息sound,要排除自己和好友发送的语音信息
        Sound sound = soundApi.getRecommendSound(UserHolder.getUserId());
        //如果查询结果为空,抛出异常
        //if (sound == null) {
         //   throw new BusinessException(ErrorResult.acceptTimeError());
        //}
        //接收成功,将sound的state设置为1
        //sound.setState("1");
        //soundApi.updateById(sound);
        //构造vo对象
        //根据sound获取用户详情
        Long userId = sound.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        SoundVo vo = new SoundVo();
        vo.setId(userId);
        vo.setAvatar(userInfo.getAvatar());
        vo.setNickname(userInfo.getNickname());
        vo.setGender(userInfo.getGender());
        vo.setAge(userInfo.getAge());
        vo.setSoundUrl(sound.getSoundUrl());
        //将剩余次数减1
        Integer value = Integer.valueOf(time);
        value -= 1;
        vo.setRemainingTimes(value);
        //将redis中的次数减1
        redisTemplate.opsForValue().set(key,value.toString(),getNowToNextDaySeconds(),TimeUnit.SECONDS);
        //返回结果
        return vo;
    }
}
